package com.alibaba.nacos.example.spring.controller;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.ClientFactory;
import com.netflix.client.http.HttpRequest;
import com.netflix.client.http.HttpResponse;
import com.netflix.config.ConfigurationManager;
import com.netflix.niws.client.http.RestClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

@Controller
@RequestMapping("discovery")
public class DiscoveryController {

    @NacosInjected
    private NamingService namingService;

    @RequestMapping(value = "/get", method = GET)
    @ResponseBody
    public List<Instance> get(@RequestParam String serviceName) throws NacosException {
        return namingService.getAllInstances(serviceName);
    }


    //    @Autowired
    private final RestTemplate restTemplate;

    @Autowired
    public DiscoveryController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }



    @RequestMapping(value = "echo", method = RequestMethod.GET)
    @ResponseBody
    public String echo(@RequestParam String str) throws NacosException {

        List<Instance> instances = namingService.getAllInstances("service-provider");
        if (!instances.isEmpty()) {

            List<String> urlList = new ArrayList<String>();
            for (Instance instance : instances) {
                String url = instance.getIp() + ":" + instance.getPort();
                System.out.println("serviceName url  is " + url);
                urlList.add(url);
            }
            String urlListStr = StringUtils.join(urlList,",");

            try {
                // 写入服务列表
                ConfigurationManager.getConfigInstance().setProperty("service-provider.ribbon.listOfServers", urlListStr);
                // 输出服务列表
                System.out.println("服务列表：" + ConfigurationManager.getConfigInstance().getProperty("service-provider.ribbon.listOfServers"));
                // 获取客户端（如果获取不到，可通过getNamedClient方法自动创建）
                RestClient client = (RestClient) ClientFactory.getNamedClient("service-provider");
                // 创建request对象
                HttpRequest request = HttpRequest.newBuilder().uri(new URI("/echo/asdf")).build();// 写入将要访问的接口
                // 多次访问测试
                for (int i = 0; i < 10; i++) {
                    // 创建response对象
                    HttpResponse response = client.executeWithLoadBalancer(request);
                    // 接收请求结果
                    String json = response.getEntity(String.class);
                    // 打印结果
                    System.out.println(json);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


            return null;
        } else {
            return restTemplate.getForObject("http://service-provider/echo/" + str, String.class);
        }





//         String rusult = restTemplate.getForObject("http://service-provider/echo/" + str, String.class);
//        return rusult;

    }




}
